import { ThemeChange } from '@shared/events.d';
import { ThemeMode } from '@shared/types.d';
import { BrowserWindow, nativeTheme } from 'electron';

import { log } from './logger';

class ThemeManager {
  setTheme(theme: ThemeMode) {
    log.info('Setting theme to', theme);
    const notifyThemeChange = () => {
      const windows = BrowserWindow.getAllWindows();
      windows.forEach((win) =>
        win.webContents.send(ThemeChange, nativeTheme.shouldUseDarkColors ? ThemeMode.dark : ThemeMode.light)
      );
    };

    if (theme === ThemeMode.auto) {
      nativeTheme.themeSource = 'system';
      nativeTheme.on('updated', notifyThemeChange);
    } else {
      nativeTheme.themeSource = theme;
      nativeTheme.removeAllListeners('updated');
    }
    notifyThemeChange();
  }

  getTheme() {
    log.info('Getting theme');
    return nativeTheme.shouldUseDarkColors ? ThemeMode.dark : ThemeMode.light;
  }
}

const themeManager = new ThemeManager();
export default themeManager;
